import type { ReactElement } from 'react';
import React, { lazy } from 'react';
//异常组件
export const NotFound = lazy(() => import('@/pages/404'));
export const InventoryAnalysisDetail: any = lazy(() => import('@/pages/InventoryAnalysis/Detail'));

export type RouteItemType = {
  type?: string;
  name?: string;
  icon?: string | ReactElement;
  label?: string;
  redirect?: string;
  routes?: RouteItemType[];
  children?: RouteItemType[];
  component?: string;
  filePath?: string;
  element?: any;
};

export const lazyFn = (name: any) => {
  const Element = lazy(() => import(`@/pages/${name}`));
  return Element;
  // return <Element />;
};
export const reduceRoute: (params: any[]) => any[] = (routes: RouteItemType[]) => {
  return routes.map((item) => {
    const route: any = item;
    if (item.children) {
      route.routes = reduceRoute(item.children);
    }
    if (item?.element || item?.filePath) {
      // 判断是否是ReactElement
      if (React.isValidElement(item.element)) {
        // 02
        route.element = item.element;
      } else {
        const element = item.element as string;
        const filePath = item.filePath as string;
        route.component = `@/pages/${filePath || element}`;
        const MyAsyncComponent = lazyFn(`${filePath || element}`);
        route.component = MyAsyncComponent || element;
        route.element = MyAsyncComponent || element;
        // route.element = <Suspense>{MyAsyncComponent}</Suspense>;
      }
    } else {
      // element不存在的情况
      route.component = NotFound;
      route.element = NotFound;
      // route.element = <NotFound />;
    }
    if (item?.redirect) {
      route.redirect = item.redirect;
    }
    if (item?.label) {
      item.name = item.label;
    }
    return route;
  });
};

export const getFlatRoute = (routes: any[], ret: any[] = []) => {
  routes.forEach((route) => {
    if (route.routes) {
      ret = getFlatRoute(route.routes, ret);
    } else {
      ret.push(route);
    }
  });
  return ret;
};

// 获取主路由
export function getAllRoutes(menuJson: any[] = []) {
  const dynamicRoutes = reduceRoute(menuJson) || [];
  const flatRoutes = getFlatRoute(dynamicRoutes);
  const routes = [
    ...flatRoutes,
    {
      path: '/user',
      layout: false,
      routes: [
        {
          path: '/user',
          routes: [
            {
              name: 'login',
              path: '/user/login',
              component: './user/Login',
            },
          ],
        },
      ],
    },
    {
      flatMenu: true,
      access: 'main',
      routes: flatRoutes,
    },
    {
      name: '404',
      component: './404',
    },
  ];
  return routes;
}
